//
//  PickNum7lcViewController.m
//  PlayBall
//
//  Created by Sun Fanglei on 13-3-27.
//
//

#import "JddPickNum7lcViewController.h"
#import "JddCommonFunction.h"
#import "JddViewControllerManager.h"
#import "NoticeViewController.h"

@interface JddPickNum7lcViewController ()

@end

@implementation JddPickNum7lcViewController

@synthesize moneyLabel;
@synthesize countLabel;
@synthesize issueLabel;
@synthesize endTimeLabel;
@synthesize currentLotteryIssue;

SHARED_VIEW_CONTROLLER_IMPLEMENT(JddPickNum7lcViewController);


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView.message isEqualToString:@"您还没有登录，请先登录"]) {
        if (buttonIndex == 0) {
            countLabel.text = @"0注";
            moneyLabel.text = @"0彩豆";
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOGIN fromController:self withObject:nil withObject2:nil];
        }
    }
}

/**
 shark phone to get random number
 */
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
    static NSDate *shakeStart;
    NSDate *now = [[NSDate alloc] init];
    NSDate *checkDate = [[NSDate alloc] initWithTimeInterval:1.5f sinceDate:shakeStart];
    if ([now compare:checkDate] == NSOrderedDescending || shakeStart == nil)
        {
        sharkCount = 0;
        shakeStart = [[NSDate alloc] init];
        }
    if (!sharked&&(fabsf(acceleration.x) > 1.0 || fabsf(acceleration.y) > 1.0 || fabsf(acceleration.z) > 1.1))
        {
        sharkCount++;
        }
    if (sharkCount > 0){
        sharkCount = 0;
        shakeStart = [[NSDate alloc] init];
        [self getRandomnum];
       
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
}

-(void)destoryView{
    [lotteryNumber clear];
    countLabel.text = @"0注";
    moneyLabel.text = @"0彩豆";
    [UIAccelerometer sharedAccelerometer].delegate = nil;
    sharked = true;
    for (UIView *subView in self.view.subviews) {
        if (subView.tag == 88) {
            [((UIButton*)subView) setSelected:NO];
        }
    }
}

-(void)listSelect{
//    CGRect rect = [[UIScreen mainScreen] bounds];
//    rect.origin.x = (rect.size.width) / 2.0;
//    rect.origin.y = (rect.size.height) / 2.0;
//    rect.size.width = 251.0;
//    rect.size.height = 300.0;
//    indexList = [JddIndexListView getInstanceView];
//    [indexList setFrame:rect];
//    indexList.type = 0;
//    indexList.delegate = self;
//    [indexList show];
    NoticeViewController *noticeView = [[NoticeViewController alloc] init];
    noticeView.webInfoId = LOTTERY_TYPE_ID_7LC;
    [self.navigationController pushViewController:noticeView animated:YES];
}
//now this delegate is rejection
//- (void)RandomSelectNumViewClickedButtonAtIndex:(NSNumber*)buttonIndex multiple:(NSNumber*)multiple{
//    if ([buttonIndex intValue]== 1) {
//        
//        [lotteryNumberArray removeAllObjects];
//        
//        for (int i = 0; i < [multiple intValue]; ++i) {
//            JddShuangSeQiuNumber *number = [[JddShuangSeQiuNumber alloc] init];
//            [JddCommonFunction generateball:number max:30 count:7];
//            
//            [lotteryNumberArray addObject:number];
//        }
//        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_7L_LIST fromController:self withObject:lotteryNumberArray withObject2:nil];
//    }
//}

/**
 获取随机号码
 **/
-(void)getRandomnum{
    [lotteryNumber clear];
    [JddCommonFunction generateball:lotteryNumber max:30 count:7];
    float delay = 0.0f;
    for (UIView *subView in self.view.subviews) {
        if ([[subView class] isSubclassOfClass:[UIButton class]] && subView.tag == 88) {
            BOOL shouldSelected = NO;
            if ([lotteryNumber redBallHasNumber:[((UIButton*)subView).titleLabel.text intValue]]) {
                shouldSelected = YES;
                [JddCommonFunction animationViewWithZoomOutIn:subView delaySecond:(delay+=0.05)];
            }
            [((UIButton*)subView) setSelected:shouldSelected];
        }
    }
    //caculate count and money
    NSInteger countTemp = [JddCommonFunction recurseBallNumber:[lotteryNumber.redBallArray count]combinationNumber:7];
    countLabel.text = [NSString stringWithFormat:@"%d注",countTemp];
    moneyLabel.text = [NSString stringWithFormat:@"%d彩豆",countTemp*2];
}
//
//-(void)selectorbutton1{
//    [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_LOTTERY_OPEN_LIST
//                                                         fromController:self
//                                                             withObject:@"13"
//                                                            withObject2:nil];
//}
//
//-(void)selectorbutton2{
//    if (![JddCommonFunction isLogin]) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"玩球球"
//                                                        message:@"您还没有登录，请先登录"
//                                                       delegate:self
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:@"取消", nil]
//        ;
//        [alert show];
//    }else {
//        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_BUY_HISTORY
//                                                             fromController:self
//                                                                 withObject:[NSNumber numberWithInt:LOTTERY_TYPE_ID_7LC]
//                                                                withObject2:nil];
//    }
//}
//
//-(void)selectorbutton3{
//    [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_HOW_TO_PLAY_SSQ
//                                                         fromController:self
//                                                             withObject:nil
//                                                            withObject2:nil];
//}
//
//-(void)selectorbutton4{
//    if (![JddCommonFunction isLogin]) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"玩球球"
//                                                        message:@"您还没有登录，请先登录"
//                                                       delegate:self
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:@"取消", nil]
//        ;
//        [alert show];
//    }else {
//        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_FOLLOW_NUMBER_HISTORY
//                                                             fromController:self
//                                                                 withObject:nil
//                                                                withObject2:nil];
//    }
//}

-(void)countDownTime:(NSTimer *)thisTimer{
    currentTime = [currentTime dateByAddingTimeInterval:1];
    
    NSTimeInterval interval = [endTime timeIntervalSinceDate:currentTime];
    if (interval < 0) {
        [countDownTimer invalidate];
        JddQueryDigitalLotteryIssueOperation *operation = [[JddQueryDigitalLotteryIssueOperation alloc] init];
        operation.delegate = self;
        operation.lotteryTypeId = @"13";
        [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
        
    }else {
        NSInteger remainDay = interval / 86400;
        NSInteger remainHour = (interval - 86400 * remainDay) / 3600;
        NSInteger remainMinute = (interval - 86400 * remainDay - remainHour * 3600) / 60;
        NSInteger remainSecond = (interval - 86400 * remainDay - remainHour *3600 - remainMinute * 60);
        endTimeLabel.text = [NSString stringWithFormat:@"%d天%d小时%d分%d秒", remainDay, remainHour, remainMinute, remainSecond];
    }

}

-(void)QueryDigitalLotteryIssueOperationResult:(NSData *)result{
    if (result) {
        if ([JddDataParser parseLotteryIssueResult:result lotteryIssue:currentLotteryIssue]){
            issueLabel.text = [NSString stringWithFormat:@"第%@期",currentLotteryIssue.name];
            
            endTime = [JddCommonFunction dateFromString:currentLotteryIssue.endTime];
            currentTime = [JddCommonFunction dateFromString:currentLotteryIssue.currentTime];
            
            countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1
                                                              target:self
                                                            selector:@selector(countDownTime:)
                                                            userInfo:nil
                                                             repeats:YES];
        }
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)loadNavBar
{
    UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
    right.frame = CGRectMake(0, 0, 40, 30);
    [right setTitle:@"帮助" forState:UIControlStateNormal];
    right.titleLabel.font = [UIFont systemFontOfSize:15];
    [right setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [right addTarget:self action:@selector(listSelect) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:right];
    
}
//- (void)backView
//{
//    [self.navigationController popViewControllerAnimated:YES];
//}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    sharked = TRUE;
    [self loadNavBar];
//    [self.navigationItem setTitle:PAGE_7L_PICK_NUMBER];
        UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
        customLab.backgroundColor = [UIColor clearColor];
        [customLab setText:PAGE_7L_PICK_NUMBER];
        customLab.textAlignment = NSTextAlignmentCenter;
        [customLab setTextColor:[UIColor whiteColor]];
        customLab.font = [UIFont systemFontOfSize:19];
        self.navigationItem.titleView = customLab;
    
    currentLotteryIssue = [[JddLotteryIssue alloc] init];
    lotteryNumber = [[JddShuangSeQiuNumber alloc] init];
    lotteryNumberArray = [NSMutableArray array];
    
    [[UIAccelerometer sharedAccelerometer] setDelegate:self];
    [[UIAccelerometer sharedAccelerometer] setUpdateInterval:1.0];
    

}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"7LC"];
    [MobClick event:@"Lottery-7LC"];
    
    [[UIAccelerometer sharedAccelerometer] setDelegate:self];
    [[UIAccelerometer sharedAccelerometer] setUpdateInterval:1.0];
    sharkCount = 0;
    sharked = false;
    [countDownTimer invalidate];
    JddQueryDigitalLotteryIssueOperation *operation = [[JddQueryDigitalLotteryIssueOperation alloc] init];
    operation.delegate = self;
    operation.lotteryTypeId = @"13";
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    [self getRandomnum];
}

-(void)viewWillDisappear:(BOOL)animated{
    [MobClick endLogPageView:@"7LC"];

    [countDownTimer invalidate];
    [UIAccelerometer sharedAccelerometer].delegate = nil;
    sharked = true;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setIssueLabel:nil];
    [self setEndTimeLabel:nil];
    [self setCountLabel:nil];
    [self setMoneyLabel:nil];
    [super viewDidUnload];
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
    return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)clearBtn:(id)sender {
    [lotteryNumber clear];
    countLabel.text = @"0注";
    moneyLabel.text = @"0彩豆";
    for (UIView *subView in self.view.subviews) {
        if (subView.tag == 88) {
            [((UIButton*)subView) setSelected:NO];
        }
    }
}

- (IBAction)randomBtn:(id)sender {
    
//    CGRect rect = [[UIScreen mainScreen] bounds];
//    rect.origin.x = (rect.size.width - 251) / 2.0;
//    rect.origin.y = (rect.size.height - 139) / 2.0;
//    rect.size.width = 251.0;
//    rect.size.height = 139.0;
//    randomSelectNumberDialog = [JddRandomSelectNumView getInstanceView];
//    [randomSelectNumberDialog setFrame:rect];
//    randomSelectNumberDialog.type =1;
//    randomSelectNumberDialog.delegate = self;
//    [randomSelectNumberDialog show];
    if (((UIView*)sender).tag == 10) {
        [self getRandomnum];
    }else{
        [lotteryNumberArray removeAllObjects];
        for (int i = 0; i < 5; ++i) {
            JddShuangSeQiuNumber *number = [[JddShuangSeQiuNumber alloc] init];
            [JddCommonFunction generateball:number max:30 count:7];
            [lotteryNumberArray addObject:number];
        }
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_7L_LIST fromController:self withObject:lotteryNumberArray withObject2:nil];
    }
//    UIButton *btn = sender;
//    [self getRandomnum];
//    [btn setEnabled:YES];
}

- (IBAction)doneBtn:(id)sender {
    
    if ([[JddPickNum7lcListViewController sharedInstance].lotNumListTable numberOfRowsInSection:0]>0) {
        if ([lotteryNumber.redBallArray count] < 7) {
             [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_7L_LIST fromController:self withObject:nil withObject2:nil];
        }else{
            [lotteryNumberArray removeAllObjects];
            JddShuangSeQiuNumber *newNum = [[JddShuangSeQiuNumber alloc] init];
            [newNum.redBallArray addObjectsFromArray:lotteryNumber.redBallArray];
            [lotteryNumberArray addObject:newNum];
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_7L_LIST fromController:self withObject:lotteryNumberArray withObject2:nil];
        }
    } else {
        if ([lotteryNumber.redBallArray count] < 7) {
            [JddCommonFunction messageBoxWithMessage:PICK_NUM_11S5_NOT_CORRECT_7];
        }else{
            [lotteryNumberArray removeAllObjects];
            JddShuangSeQiuNumber *newNum = [[JddShuangSeQiuNumber alloc] init];
            [newNum.redBallArray addObjectsFromArray:lotteryNumber.redBallArray];
            [lotteryNumberArray addObject:newNum];
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_7L_LIST fromController:self withObject:lotteryNumberArray withObject2:nil];
        }
    }
}

- (IBAction)numberBtn:(id)sender {
    UIButton *btn = sender;
    if (btn.tag == 88) {
        [btn setSelected:![btn isSelected]];
        if ([btn isSelected]) {
            [lotteryNumber addRedBallNumber:[btn.titleLabel.text intValue]];
            [JddCommonFunction animationViewWithZoomOutIn:btn delaySecond:0];
        }else{
            [lotteryNumber removeRedBallNumber:[btn.titleLabel.text intValue]];
        }
    }
    //计算注数金额
    NSInteger countTemp = [JddCommonFunction recurseBallNumber:[lotteryNumber.redBallArray count]combinationNumber:7];
    countLabel.text = [NSString stringWithFormat:@"%d注",countTemp];
    moneyLabel.text = [NSString stringWithFormat:@"%d彩豆",countTemp*2];
}
@end
